package reina.yuval.usbmonitor;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

public class MainActivity extends Activity {
	
	private static String TAG =  "UsbMonitorActivity";


	static Button btnSend;
	static EditText etSendString;
	static Spinner spnSpeed;
	static Spinner spnUsbType;
	static Spinner spnEnding;
	static TextView tvReceived;
	static ScrollView svReceived;
	static UsbManager mUsbManager;
	StringBuilder sbReceived;
	private UsbSerialDriver mSerialDevice;
	private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		
		btnSend=(Button)findViewById(R.id.btnSend);
		etSendString=(EditText)findViewById(R.id.etSend);
		tvReceived=(TextView)findViewById(R.id.tvReceived);
		svReceived=(ScrollView)findViewById(R.id.svReceived);
		spnSpeed=(Spinner)findViewById(R.id.spnSpeed);
		spnUsbType=(Spinner)findViewById(R.id.spnUsbType);
		spnEnding=(Spinner)findViewById(R.id.spnEnding);
		
		etSendString.setOnEditorActionListener(new SendAction());
		
		
	}
	
	   protected void onPause() {
	       super.onPause();
	       stopIoManager();
	       if (mSerialDevice != null) {
	           try {
	               mSerialDevice.close();
	           } catch (IOException e) {
	               // Ignore.
	           }
	           mSerialDevice = null;
	       }
	   }

	   @Override
	   protected void onResume() {
	       super.onResume();
	       mSerialDevice = UsbSerialProber.acquire(mUsbManager);
	       Log.d(TAG, "Resumed, mSerialDevice=" + mSerialDevice);
	       if (mSerialDevice == null) {
	    	   tvReceived.setText("No serial device.");
	       } else {
	           try {
	               mSerialDevice.open();
	           } catch (IOException e) {
	               Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
	               tvReceived.setText("Error opening device: " + e.getMessage());
	               try {
	                   mSerialDevice.close();
	               } catch (IOException e2) {
	                   // Ignore.
	               }
	               mSerialDevice = null;
	               return;
	           }
	           tvReceived.setText("Serial device: " + mSerialDevice);
	       }
	       onDeviceStateChange();
	   }

	
	private SerialInputOutputManager mSerialIoManager;
	
	private final SerialInputOutputManager.Listener mListener =
			new SerialInputOutputManager.Listener() {

	       
	       	public void onRunError(Exception e) {
	           Log.d(TAG, "Runner stopped.");
	       	}

	       
	       	public void onNewData(final byte[] data) {
	       		MainActivity.this.runOnUiThread(new Runnable() {
	               
	       			public void run() {
	                   MainActivity.this.updateReceivedData(data);
	               }
	           });
	       }
	};
	   
	void updateReceivedData(final byte[] data) {
		try {
			tvReceived.append(new String(data, "UTF8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		svReceived.smoothScrollTo(0, tvReceived.getBottom());

		
	}
	   
	private void stopIoManager() {
		if (mSerialIoManager != null) {
			Log.i(TAG, "Stopping io manager ..");
			mSerialIoManager.stop();
	        mSerialIoManager = null;
		}
	}

	private void startIoManager() {
		if (mSerialDevice != null) {
	           Log.i(TAG, "Starting io manager ..");
	           mSerialIoManager = new SerialInputOutputManager(mSerialDevice, mListener);
	           mExecutor.submit(mSerialIoManager);
		}
	}

	private void onDeviceStateChange() {
	       stopIoManager();
	       startIoManager();
	}
	   
	class SendAction implements OnEditorActionListener {
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (actionId == EditorInfo.IME_ACTION_SEND) {
				mSerialIoManager.writeAsync(buildMsg(v.getText().toString(),String.valueOf(spnEnding.getSelectedItem())));
				return true;
			}
			return false;
		}
	}
	
	private byte[] buildMsg(String strData, String ending) {
		return strData+ending; // must build bytes from string
	}

}

/* Copyright 2011 Google Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
* USA.
*
* Project home page: http://code.google.com/p/usb-serial-for-android/
*/

/*package com.hoho.android.usbserial.examples;

import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hoho.android.usbserial.R;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* A sample Activity demonstrating USB-Serial support.
*
* @author mike wakerly (opensource@hoho.com)
*/ /*
public class DemoActivity extends Activity {

   private final String TAG = DemoActivity.class.getSimpleName();

   /**
    * The device currently in use, or {@code null}.
    *//*
   private UsbSerialDriver mSerialDevice;

   /**
    * The system's USB service.
    *//*
   private UsbManager mUsbManager;

   private TextView mTitleTextView;
   private TextView mDumpTextView;
   private ScrollView mScrollView;

   private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();

   private SerialInputOutputManager mSerialIoManager;

   private final SerialInputOutputManager.Listener mListener =
           new SerialInputOutputManager.Listener() {

       @Override
       public void onRunError(Exception e) {
           Log.d(TAG, "Runner stopped.");
       }

       @Override
       public void onNewData(final byte[] data) {
           DemoActivity.this.runOnUiThread(new Runnable() {
               @Override
               public void run() {
                   DemoActivity.this.updateReceivedData(data);
               }
           });
       }
   };

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
       mTitleTextView = (TextView) findViewById(R.id.demoTitle);
       mDumpTextView = (TextView) findViewById(R.id.demoText);
       mScrollView = (ScrollView) findViewById(R.id.demoScroller);
   }

   @Override
   protected void onPause() {
       super.onPause();
       stopIoManager();
       if (mSerialDevice != null) {
           try {
               mSerialDevice.close();
           } catch (IOException e) {
               // Ignore.
           }
           mSerialDevice = null;
       }
   }

   @Override
   protected void onResume() {
       super.onResume();
       mSerialDevice = UsbSerialProber.acquire(mUsbManager);
       Log.d(TAG, "Resumed, mSerialDevice=" + mSerialDevice);
       if (mSerialDevice == null) {
           mTitleTextView.setText("No serial device.");
       } else {
           try {
               mSerialDevice.open();
           } catch (IOException e) {
               Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
               mTitleTextView.setText("Error opening device: " + e.getMessage());
               try {
                   mSerialDevice.close();
               } catch (IOException e2) {
                   // Ignore.
               }
               mSerialDevice = null;
               return;
           }
           mTitleTextView.setText("Serial device: " + mSerialDevice);
       }
       onDeviceStateChange();
   }

   private void stopIoManager() {
       if (mSerialIoManager != null) {
           Log.i(TAG, "Stopping io manager ..");
           mSerialIoManager.stop();
           mSerialIoManager = null;
       }
   }

   private void startIoManager() {
       if (mSerialDevice != null) {
           Log.i(TAG, "Starting io manager ..");
           mSerialIoManager = new SerialInputOutputManager(mSerialDevice, mListener);
           mExecutor.submit(mSerialIoManager);
       }
   }

   private void onDeviceStateChange() {
       stopIoManager();
       startIoManager();
   }

   private void updateReceivedData(byte[] data) {
       final String message = "Read " + data.length + " bytes: \n"
               + HexDump.dumpHexString(data) + "\n\n";
       mDumpTextView.append(message);
       mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
   }

}
*/
